package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.goods.DD373API;
import com.ruoyi.system.outto.goods.NEWTHGAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class DD373APIImpl implements DD373API {

    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    InterAttrMapper interAttrMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "goods.add", salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpRequest.post("https://goods.dd373.com/Api/Open/Third").body(JSONObject.toJSONString(params)).execute().body();
        log.info("DD373添加接口请求参数={}", JSONObject.toJSONString(params));
        log.info("DD373添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("ResultCode"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
            String resultData = resultJson.getString("ResultData");
            String shopNo = JSONObject.parseObject(resultData).getString("ShopNo");
            result.put("outId", shopNo);
        }
        result.put("msg", resultJson.getString("msg"));
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> params = params(goodsInfoAndAttrValueDto, "goods.update", salePartner);
        Map<String, Object> result = new HashMap<>();
        String response = HttpRequest.post("https://goods.dd373.com/Api/Open/Third").body(JSONObject.toJSONString(params)).execute().body();
        log.info("DD373编辑接口请求参数={}", JSONObject.toJSONString(params));
        log.info("DD373编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"0".equals(resultJson.getString("ResultCode"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("msg", resultJson.getString("msg"));
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,JSONObject jsonObject, String server) {
        //========================开始匹配区服属性=====================//
        JSONObject jsonObject2 = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = jsonObject2.getString("interServeReqs");
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (goodsInfoAndAttrValueDto.getSystemId().toString().equals(ydServeId)) {
                        String interServerRes = object.getString("interServerRes");
                        if(StringUtils.isNotEmpty(interServerRes)){
                            List<JSONObject> twoServer = JSONObject.parseArray(interServerRes, JSONObject.class);
                            for (JSONObject object2 : twoServer) {
                                String ydServeId2 = object2.getString("YdServeId");
                                ydServeId2 = ydServeId2.replace(",", "").replace(" ", "");
                                if (goodsInfoAndAttrValueDto.getCarrierId().toString().equals(ydServeId2)) {
                                    String interServerRes3 = object2.getString("interServerRes");
                                    if(StringUtils.isNotEmpty(interServerRes3)) {
                                        List<JSONObject> three = JSONObject.parseArray(interServerRes3, JSONObject.class);
                                        if (three.size() == 1) {
                                            jsonObject.put("LastId", three.get(0).getString("id"));
                                            break;
                                        }
                                    }else {
                                        jsonObject.put("LastId",object2.getString("id"));
                                    }
                                }
                            }
                        }else {
                            jsonObject.put("LastId",object.getString("id"));
                        }
                    }
                }
            }
        } else {
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);
            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    if(ydServeId.equals(goodsInfoAndAttrValueDto.getGroupId().toString())){
                        String interServerRes = object.getString("interServerRes");
                        if(StringUtils.isNotEmpty(interServerRes)) {
                            List<JSONObject> oneServers = JSONObject.parseArray(interServerRes, JSONObject.class);
                            for (JSONObject object2 : oneServers) {
                                ydServeId = object2.getString("YdServeId");
                                if (StringUtils.isNotEmpty(ydServeId)) {
                                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                                    if (StringUtils.equals(goodsInfoAndAttrValueDto.getServerId().toString(), ydServeId)) {
                                        jsonObject.put("LastId", object2.getString("id"));
                                        break;
                                    }
                                }
                            }
                        }else {
                            jsonObject.put("LastId", object.getString("id"));
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 开始匹配单选属性
     *
     * @param goodsInfoAndAttrValueDto
     * @param radioAttr
     */
    private String builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String radioAttr, String optionss) {
        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (!org.springframework.util.CollectionUtils.isEmpty(jsonObjects)) {
            /**
             * 1、先查询自定义中所有单选的字段
             * 2、再查该账号单选字段中的选项
             * 3、再去接口属性匹配表过滤
             */
            GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
            gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
            gameAttrTemplate.setIsEnable("0");
            gameAttrTemplate.setFieldType("radio");
            List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
            Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


            List<JSONObject> defObjects = new ArrayList<>();

            defObjects.addAll(jsonObjects);
            for (JSONObject object : jsonObjects) {
                for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                    List<Object> list = new ArrayList<>();
                    String fieldName = "";
                    String aavName = attrTemplate.getAavName();
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (aavName.equals(name)) {
                            //一级属性
                            //注意 YdConfigId 对应的是 f字段对应的 id
                            if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                                String InterConfigId = object.getString("InterConfigId");
                                defObjects.remove(object);//如果匹配上，则去掉
                                String interRadioReqs1 = object.getString("interRadioReqs");
                                List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                                declaredField.setAccessible(true);
                                try {
                                    //获取选择的值 例如  实名中的可二次
                                    Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                    String oneValue = String.valueOf(o);
                                    List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> Objects.equals(j.getString("YdConfigId"), oneValue)).collect(Collectors.toList());
                                    String interConfigName = object.getString("InterConfigName");
                                    String defaultValue = object.getString("defaultValue");
                                    if (org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        if (StringUtils.isNotEmpty(defaultValue)) {
//                                        mateMap.put("id", InterConfigId);
//                                        mateMap.put("val", defaultValue);
                                            fieldName = InterConfigId;
                                            list.add(defaultValue);
                                        }
                                    }
//                                if (org.springframework.util.CollectionUtils.isEmpty(twoAttr) && StringUtils.isEmpty(defaultValue)) {
//                                    throw new GlobalException("属性" + interConfigName + " 接口要求必传，但是暂未匹配到，请设置默认值");
//                                }
                                    if (!org.springframework.util.CollectionUtils.isEmpty(twoAttr)) {
                                        JSONObject jsonObject2 = twoAttr.get(0);
                                        String interConfigId2 = jsonObject2.getString("name");
                                        fieldName = InterConfigId;
                                        list.add(interConfigId2);
                                    }
                                } catch (Exception e) {
                                    throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                            }
                        }
                    }
                    if (StringUtils.isNotEmpty(list)) {
                        String join = StringUtils.join(list, ",");
                        String xingyuanzhencang = fieldName+"=" + join;
                        optionss += "^123|^" + xingyuanzhencang;
                    }
                }
            }
            //开始匹配默认值
            for (JSONObject object : defObjects) {
                List<Object> list = new ArrayList<>();
                String fieldName = object.getString("defaultValue");
                interRadioReqs = object.getString("interRadioReqs");
                jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
                for (JSONObject objects : jsonObjects) {
                    if(StringUtils.isNotEmpty(objects.getString("defaultValue"))){
                        list.add(objects.getString("defaultValue"));
                    }
                }
                if (StringUtils.isNotEmpty(list)) {
                    String join = StringUtils.join(list, ",");
                    String xingyuanzhencang = fieldName+"=" + join;
                    optionss += "^123|^" + xingyuanzhencang;
                }
            }
        }
        return optionss;
        //========================单选属性匹配结束=====================//
    }
    private String builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String checkAttr, String optionss) {
        JSONObject checkOtherJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkOtherJson.getString("interCheckBoxReqs");
        Map<String, List<JSONObject>> otherMap = new HashMap<>();
        if (!StringUtils.isEmpty(interCheckBoxReqs)) {
            List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
            checkJsonList = checkJsonList.stream().filter(s -> StringUtils.isNotEmpty(s.getString("YdConfigId"))).collect(Collectors.toList());
            otherMap = checkJsonList.stream().collect(Collectors.groupingBy(s -> s.getString("YdConfigId")));

        }
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        if (org.springframework.util.CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        List<String> paramList = new ArrayList<>();

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
            //属性配置F字段Key
            String aavName = attrTemplate.getAavName();
            for (Field declaredField : declaredFields) {
                String name = declaredField.getName();
                if (aavName.equals(name)) {
                    declaredField.setAccessible(true);
                    Object o = null;
                    try {
                        o = declaredField.get(goodsInfoAndAttrValueDto);
                    } catch (IllegalAccessException e) {
                        throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                    }
                    String oneValue = String.valueOf(o);
                    if (StringUtils.isNotEmpty(oneValue)) {
                        List<String> list = Arrays.asList(oneValue.split(","));
                        paramList.addAll(list);
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(paramList)) {
            paramList = new ArrayList<>(new HashSet<>(paramList));
        }
        // 整合虞都有的属性
//        List<JSONObject> dataList = new ArrayList<>();
//        for (String str : paramList) {
//            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(otherMap.get(str))) {
//                JSONObject json = otherMap.get(str).get(0);
//                dataList.add(json);
//            }
//        }
//        Map<String, List<JSONObject>> collect = dataList.stream().collect(Collectors.groupingBy(s -> s.getString("id")));

        //获取线上属性
        List<JSONObject> list = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (!CollectionUtils.isEmpty(list)) {
            for (JSONObject jsonObject : list) {
                String fieldName = jsonObject.getString("id");
                List<Object> list2 = new ArrayList<>();
                List<JSONObject> interServerRes = JSONObject.parseArray(jsonObject.getString("interServerRes"), JSONObject.class);
                if (!CollectionUtils.isEmpty(interServerRes)) {
                    for (JSONObject interServerRe : interServerRes) {
                        if (paramList.contains(interServerRe.getString("YdConfigId"))) {
//                            JSONObject object = interServerRe;
                            list2.add(interServerRe.getString("id"));
                        }
                    }
                    if (!CollectionUtils.isEmpty(list2)) {
                        String join = StringUtils.join(list2, ",");
                        String xingyuanzhencang = fieldName+"=" + join;
                        optionss += "^123|^" + xingyuanzhencang;
                    }
                }
            }
        }
//        for (JSONObject object : checkJsonList) {
//            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
//                List<Object> list = new ArrayList<>();
//                String fieldName = "";
//                String aavName = attrTemplate.getAavName();
//                for (Field declaredField : declaredFields) {
//                    String name = declaredField.getName();
//                    if (aavName.equals(name)) {
//                        declaredField.setAccessible(true);
//
////                        List<String> list2 = new ArrayList<>();
////                        for (String s : split2) {
////                            s = s.replace(" ", "");
////                            list2.add(s);
////                        }
//                        Object o = null;
//                        try {
//                            o = declaredField.get(goodsInfoAndAttrValueDto);
//                        } catch (IllegalAccessException e) {
//                            throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
//                        }
//                        String oneValue = String.valueOf(o);
//                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                        //开始匹配二级属性
//                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
//                        /**
//                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
//                         */
//                        String pf_ids = "";
//                        for (JSONObject jsonObject1 : jsonObjects2) {
//                            String[] split1 = oneValue.split(",");
//                            String ydConfigId1 = jsonObject1.getString("YdConfigId");
//                            for (String s : split1) {
//                                if (Objects.equals(s, ydConfigId1)) {
////                                    String InterConfigId2 = jsonObject1.getString("InterConfigId");
////                                    pf_ids+=","+InterConfigId2;
//                                    fieldName = object.getString("InterConfigId");
//                                    list.add(jsonObject1.getString("InterConfigId"));
//                                }
//                            }
//                        }
//                    }
//                }
//                if (StringUtils.isNotEmpty(list)) {
//                    String join = StringUtils.join(list, ",");
//                    String xingyuanzhencang = fieldName+"=" + join;
//                    optionss += "^123|^" + xingyuanzhencang;
//                }
//            }
//        }
        return optionss;
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, String type, SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();
        params.put("AppKey",salePartner.getSaleKey());
        params.put("Method",type);
        params.put("SignType","md5");
        JSONObject jsonData = new JSONObject();

        //自动匹配开始
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_")+1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        String interGameId = interAttr.getInterGameId();
        if(interGameId.contains("_")){
            interGameId = interGameId.split("_")[0];
        }

        String typeId = getTypeId(interGameId);
        jsonData.put("GoodsType",typeId);
        jsonData.put("DealType",3);
        if(type.contains("update")) {
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            ArtRec artRec = artRecs.get(0);
            jsonData.put("ShopNo", artRec.getOutid());
        }
        jsonData.put("Title", goodsInfoAndAttrValueDto.getTitle());
        jsonData.put("Price", goodsInfoAndAttrValueDto.getPrice());
        jsonData.put("Count", 1);
        jsonData.put("Account", goodsInfoAndAttrValueDto.getAccountNumber());
        jsonData.put("Password", String.valueOf(System.currentTimeMillis()).substring(3));
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String pic = infoImgs.stream().map(info -> info.getImgUrl()).collect(Collectors.toList()).stream().collect(Collectors.joining("|"));
        jsonData.put("Images", pic);
        jsonData.put("Detail", goodsInfoAndAttrValueDto.getDes());
        //属性
//        JSONArray Attrubutes = new JSONArray();
        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, jsonData, interAttr.getServer());
//        jsonData.put("Attrubutes", Attrubutes);

        params.put("JsonData",jsonData.toJSONString());
        params.put("Timestamp",String.valueOf(System.currentTimeMillis()/1000));
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1);
        cover += salePartner.getOther();
        System.out.println(cover);
        String string = DigestUtils.md5Hex(cover);
        params.put("Sign",string);
        return params;
    }

    String getTypeId(String gameId){
//        if(gameId.contains("_")){
//            gameId = gameId.split("_")[0];
//        }
        String response = HttpRequest.get("https://game.dd373.com/Api/GameGoodsType/List?parentId="+gameId).execute().body();
        String StatusData = JSONObject.parseObject(response).getString("StatusData");
        String ResultData = JSONObject.parseObject(StatusData).getString("ResultData");
        String GameGoodsType = JSONObject.parseObject(ResultData).getString("GameGoodsType");
        JSONArray jsonArray = JSONArray.parseArray(GameGoodsType);
        String typeId = "";
        for(Object o : jsonArray){
            if(JSONObject.parseObject(o.toString()).getString("Name").equals("游戏账号")){
                typeId = JSONObject.parseObject(o.toString()).getString("Id");
                break;
            }
        }
        return typeId;
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner,String operate) {
        Map<String, Object> params = new TreeMap<>();
        Map<String, Object> result = new HashMap<>();

        JSONObject jsonObject = new JSONObject();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        jsonObject.put("ShopNo",artRec.getOutid());
        jsonObject.put("Operate",operate);//上架1 下架2

        params.put("AppKey",salePartner.getSaleKey());
        params.put("Method","goods.updatestate");
        params.put("SignType","md5");
        params.put("JsonData",jsonObject.toJSONString());
        params.put("Timestamp",String.valueOf(System.currentTimeMillis()/1000));
        String cover = MapUntils.getCover(params);
        cover = cover.substring(0,cover.length()-1);
        cover += salePartner.getOther();
        System.out.println(cover);
        String string = DigestUtils.md5Hex(cover);
        params.put("Sign",string);

        String response = HttpRequest.post("https://goods.dd373.com/Api/Open/Third").body(JSONObject.toJSONString(params)).execute().body();
        log.info("DD373删除接口请求参数={}", JSONObject.toJSONString(params));
        log.info("DD373删除接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"0".equals(resultJson.getString("ResultCode"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }
        result.put("msg", resultJson.getString("msg"));
        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        return AjaxResult.success(result);
    }

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("https://imgage.maimaihao.com/logo/no_img.jpg");
        String img = uploadImg(list);
        System.out.println(img);
    }

    static String uploadImg(List<String> list){
        Map<String,Object> params = new HashMap<>();
        params.put("Images",list);
        String body = HttpRequest.post("https://goods.dd373.com/Api/OpenApi/GoodsUploadImage").body(JSONObject.toJSONString(params)).execute().body();
        return body;
    }

}
